package com.stcc.base.context;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Assert;

import java.lang.annotation.Annotation;
import java.util.Map;

public class SpringContextHolder {
    private static String ENV;
    private static ApplicationContext applicationContext;

    private SpringContextHolder() {
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static String getEnvironment() {
        if (StringUtils.isEmpty(ENV)) {
            ENV = getActiveProfile();
        }

        return ENV;
    }

    public static void setEnvironment(String env) {
        ENV = env;
    }

    public static void eventPublish(Object event) {
        applicationContext.publishEvent(event);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annType) {
        return applicationContext.getBeansWithAnnotation(annType);
    }

    public static boolean isDemoMode() {
        return isTestMode() || isDevMode();
    }

    public static boolean isDevMode() {
        return "dev".equalsIgnoreCase(getActiveProfile());
    }

    public static boolean isTestMode() {
        return "test".equalsIgnoreCase(getActiveProfile());
    }

    public static BeanDefinitionRegistry getBeanDeinitionRegistry() {
        Assert.notNull(applicationContext, "applicationContext获取失败!");
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext)applicationContext;
        return (DefaultListableBeanFactory)configurableApplicationContext.getBeanFactory();
    }
}
